/*
 * 阔地教育科技有限公司版权所有(codyy.com/codyy.cn)
 * Copyright (c) 2020, Codyy and/or its affiliates. All rights reserved.
 */

package com.codyy.lib_common.listener

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Handler
import android.provider.Settings

/**
 * created by lijian on 2020/01/09
 * 重力传感器方向管理类
 */
class OrientationSensorManager(
    private val rotateHandler: Handler?,
    private val context: Context
) {
    private var sm: SensorManager =
        context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
    private var sensor: Sensor
    private var listener: OrientationSensorListener

    init {
        sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        listener = OrientationSensorListener(rotateHandler)
    }

    /**
     * 手机旋转横屏未锁定
     */
    fun registerListener() {
        if (Settings.System.getInt(
                context.contentResolver,
                Settings.System.ACCELEROMETER_ROTATION
            ) == 1
        ) {
            unregisterListener()
            listener = OrientationSensorListener(rotateHandler)
            sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
        } else {
            unregisterListener()
        }
    }

    fun unregisterListener() {
        rotateHandler?.removeCallbacksAndMessages(null)
        sm.unregisterListener(listener)
    }
}